package com.ky.manage.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.ky.manage.BaseApplication;
import com.ky.manage.R;
import com.ky.manage.activityLifecycle.ActivityManagerUtil;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.CommonResp;
import com.ky.manage.model.response.UserHeaderImgResp;
import com.ky.manage.ui.dialog.CommonDialog;
import com.ky.manage.utils.AddressRegionSelectUtils;
import com.ky.manage.utils.ImageLoader.GlideEngine;
import com.ky.manage.utils.MMKVUtil;
import com.ky.manage.utils.ReClickHelper;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.TextHttpResponseHandler;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.fragment.app.FragmentActivity;
import cz.msebera.android.httpclient.Header;

/**
 * 个人信息页
 */
public class PersonalInfoActivity extends BaseActivity {
    private LoginUserInfo mLoginUserInfo;
    private ImageView mUserHeadIv;
    private TextView addressRegionTv, detailAddressTv, idCardValueTv;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_info;
    }

    @Override
    protected void initView() {
        getCurLoginUserInfo();

        findTextView(R.id.page_title_tv, "个人信息");
        findView(R.id.back_iv, v -> {
            finish();
        });
        findView(R.id.user_head_rl, v -> {
            //修改头像页
            if (ReClickHelper.clickEnable()) {
                showAddPicDialog();
            }
        });
        mUserHeadIv = findView(R.id.user_header_iv);
        if (!TextUtils.isEmpty(mLoginUserInfo.userHeadUrl)) {
            //ImageLoaderUtils.loadImage(this, mLoginUserInfo.userHeadUrl, mUserHeadIv);
            loadHeader();
        } else {
            mUserHeadIv.setImageDrawable(getDrawable(R.mipmap.default_user_head));
        }
        findTextView(R.id.user_name_tv, mLoginUserInfo.userName);
        findTextView(R.id.phone_value_tv, mLoginUserInfo.phone);
        findTextView(R.id.sex_value_tv, "0".equals(mLoginUserInfo.sex) ? "男" : "女");
        idCardValueTv = findTextView(R.id.id_card_value_tv, TextUtils.isEmpty(mLoginUserInfo.idCardValue) ? "点击变更"
                : mLoginUserInfo.idCardValue, v -> {
            showEditDialog("numberId", result->{
                idCardValueTv.setText(result);
            });
        });
        detailAddressTv = addressRegionTv = findTextView(R.id.address_region_tv, TextUtils.isEmpty(mLoginUserInfo.addressRegion) ? "点击选择"
                : mLoginUserInfo.addressRegion, v -> {
            doSelectRegion();
        });
        findView(R.id.address_region_rl, v -> {
            doSelectRegion();
        });
        findTextView(R.id.detail_address_tv, TextUtils.isEmpty(mLoginUserInfo.addressDetail) ? "点击变更"
                : mLoginUserInfo.addressDetail, v -> {
            showEditDialog("detailAddress", result->{
                detailAddressTv.setText(result);
            });
        });
        findView(R.id.detail_address_rl, v -> {
            showEditDialog("detailAddress", result->{
                detailAddressTv.setText(result);
            });
        });
        findTextView(R.id.ew_code_tv, TextUtils.isEmpty(mLoginUserInfo.ewCodeValue) ? "无"
                : mLoginUserInfo.ewCodeValue);
        findView(R.id.ew_code_rl, v -> {
            if (!TextUtils.isEmpty(mLoginUserInfo.ewCodeValue)) {
                toActivity(new Intent(this, EwCodeActivity.class));
            }
        });
    }

    private CommonDialog mEditDialog;

    private void showEditDialog(String key, OnEditChange onEditChange) {
        if (ActivityManagerUtil.getInstance().isActivityDestroy(this)) {
            return;
        }
        if (null == mEditDialog) {
            WeakReference<FragmentActivity> activityWeakReference = new WeakReference<>(this);
            mEditDialog = CommonDialog.create(activityWeakReference.get().getSupportFragmentManager())
                    .setLayoutRes(R.layout.dialog_edit)
                    .setViewListener(((v, baseDialog) -> {
                        if (null == activityWeakReference || null == activityWeakReference.get()
                                || activityWeakReference.get().isFinishing()) {
                            return;
                        }
                        TextView cancelTv = v.findViewById(R.id.cancel_tv);
                        cancelTv.setOnClickListener(v1 -> {
                            hideEditDialog();
                        });
                        TextView labelTv = v.findViewById(R.id.label_tv);
                        if ("numberId".equals(key)) {
                            labelTv.setText("身份证号");
                        } else if ("detailAddress".equals(key)) {
                            labelTv.setText("详细地址");
                        }
                        EditText editEt = v.findViewById(R.id.edit_et);
                        TextView okTv = v.findViewById(R.id.ok_tv);
                        okTv.setOnClickListener(v1 -> {
                            //确定变更
                            String editContent = editEt.getText().toString().trim();
                            if (TextUtils.isEmpty(editContent)) {
                                ToastUtils.showRoundRectToast("内容不能为空");
                                return;
                            }
                            updateUserInfo(key, editContent, onEditChange);
                        });
                    }))
                    .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
                    .setGravity(Gravity.CENTER)
                    .setOnDismissListener(dialog -> {
                        //对话框关闭
                        hideEditDialog();
                    })
                    .setDialogWidth(ScreenUtils.dp2px(300))
                    .setDimAmount(0.2f)
                    .setCancelOutside(false)
                    .setKeyBackDismiss(false)
                    .setTag("Editialog");
        }

        if (mEditDialog.isShowing()) {
            return;
        }
        mEditDialog.show();
    }

    private void hideEditDialog() {
        if (null != mEditDialog) {
            mEditDialog.dismissAllowingStateLoss();
            mEditDialog = null;
        }
    }

    public static interface OnEditChange {
        void onEditSuccess(String result);
    }

    private void doSelectRegion() {
        AddressRegionSelectUtils.getInstance().showRegionSelect(this, new AddressRegionSelectUtils.OnRegionSelect() {
            @Override
            public void onSelect(String result) {
                addressRegionTv.setText(result);
                updateUserInfo("areaName", result);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void updateUserInfo(String key, String value, OnEditChange onEditChange) {
        //更新区域信息
        JSONObject requestParams = new JSONObject();
        try {
            requestParams.put(key, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        AsyncHttpUtils.getInstance().put(PersonalInfoActivity.this, BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/updateUserInfo", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("updateUserInfo", "onFailure statusCode = "
                        + statusCode + ", responseString = " + responseString);
                ToastUtils.showRoundRectToast("修改失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("updateUserInfo", "onSuccess statusCode = "
                        + statusCode + ", responseString = " + responseString);
                CommonResp resp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, CommonResp.class);
                if (statusCode == 200 && null != resp && resp.code == 200) {
                    if (null != onEditChange) {
                        onEditChange.onEditSuccess(value);
                    }
                    ToastUtils.showRoundRectToast("修改成功");
                } else {
                    ToastUtils.showRoundRectToast("修改失败");
                }
            }
        });
    }
    /**
     * 变更信息
     * @param key
     * @param value
     */
    private void updateUserInfo(String key, String value) {
        updateUserInfo(key, value, null);
    }

    private void getCurLoginUserInfo() {
        mLoginUserInfo = BaseApplication.getLoginUserInfo();
        if (null == mLoginUserInfo) {
            mLoginUserInfo = new LoginUserInfo();
        }
    }

    @Override
    protected void initData() {
    }

    private CommonDialog mAddPicDialog;

    /**
     * 添加图片选择框
     */
    private void showAddPicDialog() {
        if (ActivityManagerUtil.getInstance().isActivityDestroy(this)) {
            return;
        }
        if (null == mAddPicDialog) {
            WeakReference<FragmentActivity> activityWeakReference = new WeakReference<>(this);
            mAddPicDialog = CommonDialog.create(activityWeakReference.get().getSupportFragmentManager())
                    .setLayoutRes(R.layout.dialog_add_pic)
                    .setViewListener(((v, baseDialog) -> {
                        if (null == activityWeakReference || null == activityWeakReference.get()
                                || activityWeakReference.get().isFinishing()) {
                            return;
                        }
                        TextView addPicFromCamera = v.findViewById(R.id.add_pic_camera);
                        TextView addPicFromAlbum = v.findViewById(R.id.add_pic_album);
                        TextView cancelTv = v.findViewById(R.id.cancel_tv);
                        addPicFromCamera.setOnClickListener(v1 -> {
                            //拍照获取图片
                            if (ReClickHelper.clickEnable()) {
                                //拍照
                                PictureSelector.create(this)
                                        .openCamera(PictureMimeType.ofImage())
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                hideAddPicDialog();
                            }
                        });
                        addPicFromAlbum.setOnClickListener(v1 -> {
                            //从相册获取图片
                            if (ReClickHelper.clickEnable()) {
                                PictureSelector.create(this)
                                        .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                        .maxSelectNum(1)// 最大图片选择数量
                                        .minSelectNum(1)// 最小选择数量
                                        .imageSpanCount(4)// 每行显示个数
                                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
                                        .imageEngine(GlideEngine.createGlideEngine())
                                        .isPreviewImage(true)// 是否可预览图片
                                        .isCamera(true)// 是否显示拍照按钮
                                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
//                                        .setOutputCameraPath(Environment.getExternalStorageDirectory().getPath()
//                                                + "/ky/tmpPath/")// 自定义拍照保存路径
                                        .isEnableCrop(false)// 是否裁剪
                                        .isCompress(false)// 是否压缩
                                        //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                        .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                                        .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                                        //.selectionMedia(selectList)// 是否传入已选图片
                                        //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                        //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                                        //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                                        //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                                        //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                                        .rotateEnabled(false) // 裁剪是否可旋转图片
                                        //.scaleEnabled()// 裁剪是否可放大缩小图片
                                        //.recordVideoSecond()//录制视频秒数 默认60s
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                hideAddPicDialog();
                            }
                        });
                        cancelTv.setOnClickListener(v1 -> {
                            //关闭弹框
                            hideAddPicDialog();
                        });
                    }))
                    .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
                    .setGravity(Gravity.CENTER)
                    .setOnDismissListener(dialog -> {
                        //对话框关闭
                        hideAddPicDialog();
                    })
                    .setDialogWidth(ScreenUtils.dp2px(300))
                    .setDimAmount(0.2f)
                    .setCancelOutside(false)
                    .setKeyBackDismiss(false)
                    .setTag("AddPicDialog");
        }

        if (mAddPicDialog.isShowing()) {
            return;
        }
        mAddPicDialog.show();
    }

    private void hideAddPicDialog() {
        if (null != mAddPicDialog) {
            mAddPicDialog.dismissAllowingStateLoss();
            mAddPicDialog = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                images = PictureSelector.obtainMultipleResult(data);
                if (null == images || images.size() == 0) {
                    return;
                }
                LocalMedia localMedia = images.get(0);
                File file = new File(localMedia.getPath());
                BusinessHttpReqUtils.getInstance().changeUserHeaderImg(file, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        ZyUtils.getInstance().insertLog("changeUserHeaderImg", "onFailure statusCode = " + statusCode
                                + ", responseString = " + responseString);
                        ToastUtils.showRoundRectToast("修改头像失败");
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                        ZyUtils.getInstance().insertLog("changeUserHeaderImg", "onSuccess statusCode = " + statusCode
                                + ", responseString = " + responseString);
                        if (statusCode == 200) {
                            Log.d("lhm", "changeUserHeaderImg responseString = " + responseString);
                            UserHeaderImgResp userHeaderImgResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, UserHeaderImgResp.class);
                            if (null != userHeaderImgResp && !TextUtils.isEmpty(userHeaderImgResp.imgUrl)) {
                                if (userHeaderImgResp.imgUrl.startsWith("http")) {
                                    mLoginUserInfo.userHeadUrl = userHeaderImgResp.imgUrl;
                                } else {
                                    mLoginUserInfo.userHeadUrl = BusinessHttpReqUtils.SERVICE_DOMAIN + ":8888" + userHeaderImgResp.imgUrl;
                                }
                                MMKVUtil.getInstance().saveObjectToMMKV("userInfo", mLoginUserInfo);
                                loadHeader();
                                ToastUtils.showRoundRectToast("修改头像成功");
                            } else {
                                ToastUtils.showRoundRectToast("修改头像失败");
                            }
                        } else {
                            ToastUtils.showRoundRectToast("修改头像失败");
                        }
                    }
                });
            }
        }
    }

    private void loadHeader() {
        Glide.with(this).asBitmap().centerCrop()
                .load(mLoginUserInfo.userHeadUrl)
                .placeholder(R.mipmap.default_user_head)
                .error(R.mipmap.default_user_head)
                .into(new BitmapImageViewTarget(mUserHeadIv){
                    @Override
                    protected void setResource(Bitmap resource) {
                        super.setResource(resource);
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        mUserHeadIv.setImageDrawable(circularBitmapDrawable);
                    }
                });
    }

    private String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}